﻿package org.ilanchong.droidcontroller;

import java.util.StringTokenizer;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.format.Formatter;

public class Utils {
	public static final int COMMAND_PORT = 30000;
	public static final int BROADCAST_PORT = 20000; // 广播端口
	public static final int CONNECT_TIMEOUT = 30 * 1000; // 通讯超时设置 (毫秒)
	public static final String BROADCAST_IP = "255.255.255.255"; // 广播IP
																			
	private String intToIp(int i) {
		return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
				+ "." + (i >> 24 & 0xFF);
	}
	
	public static String getLocalIP(Context context) {
		WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

		if (!wifiManager.isWifiEnabled()) {
			wifiManager.setWifiEnabled(true);
		}
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		String ip = "";
		if (wifiInfo != null) {
			ip = Formatter.formatIpAddress(wifiInfo.getIpAddress());
		}
		return ip;
	}

	public static String getPriorityIP(String substring, String localIp) {
		StringTokenizer strToken = new StringTokenizer(substring, "#");

		int max = -1;
		String priorityIp = "";

		while (strToken.hasMoreElements()) {
			String str = (String) strToken.nextElement();
			int c = compare(str, localIp);
			
			if (c > max) {
				max = c;
				priorityIp = str;
			}
		}

		return priorityIp;
	}

	private static int compare(String srcIP, String desIP) {
		int c = 0;

		StringTokenizer srcToken = new StringTokenizer(srcIP, ".");
		StringTokenizer desToken = new StringTokenizer(desIP, ".");

		while (srcToken.hasMoreElements() && desToken.hasMoreElements()) {
			String src = (String) srcToken.nextElement();
			String des = (String) desToken.nextElement();

			if (src.equals(des)) {
				c++;
			}
		}
		return c;
	}
}
